package com.umeox.calculator;

import android.content.Context;
import android.content.res.Resources;
import android.text.TextUtils;
import android.widget.EditText;

import org.javia.arity.Symbols;
import org.javia.arity.SyntaxException;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

/* access modifiers changed from: package-private */
public class Logic {
    private Context mContext;
    private int mDeleteMode = 0;
    private CalculatorDisplay mDisplay;
    private final String mErrorString;
    private History mHistory;
    private boolean mIsError = false;
    private int mLineLength = 0;
    private Listener mListener;
    private String mResult = "";
    private Symbols mSymbols = new Symbols();
    private Set<Map.Entry<String, String>> mTranslationsSet;

    public interface Listener {
        void onDeleteModeChange();
    }

    Logic(Context context, History history, CalculatorDisplay display) {
        this.mContext = context;
        this.mErrorString = this.mContext.getResources().getString(R.string.error);
        this.mHistory = history;
        this.mDisplay = display;
        this.mDisplay.setLogic(this);
    }

    public void setListener(Listener listener) {
        this.mListener = listener;
    }

    public void setDeleteMode(int mode) {
        if (this.mDeleteMode != mode) {
            this.mDeleteMode = mode;
            this.mListener.onDeleteModeChange();
        }
    }

    public int getDeleteMode() {
        return this.mDeleteMode;
    }

    /* access modifiers changed from: package-private */
    public void setLineLength(int nDigits) {
        this.mLineLength = nDigits;
    }

    /* access modifiers changed from: package-private */
    public boolean eatHorizontalMove(boolean toLeft) {
        EditText editText = this.mDisplay.getEditText();
        int cursorPos = editText.getSelectionStart();
        return toLeft ? cursorPos == 0 : cursorPos >= editText.length();
    }

    private String getText() {
        return this.mDisplay.getText().toString();
    }

    /* access modifiers changed from: package-private */
    public void insert(String delta) {
        this.mDisplay.insert(delta);
        setDeleteMode(0);
    }

    public void onTextChanged() {
        setDeleteMode(0);
    }

    public void resumeWithHistory() {
        clearWithHistory(false);
    }

    private void clearWithHistory(boolean scroll) {
        String text = this.mHistory.getText();
        if ("?".equals(text)) {
            if (!this.mHistory.moveToPrevious()) {
            }
            evaluateAndShowResult(this.mHistory.getText(), CalculatorDisplay.Scroll.NONE);
            return;
        }
        this.mResult = "";
        this.mDisplay.setText(text, scroll ? CalculatorDisplay.Scroll.UP : CalculatorDisplay.Scroll.NONE);
        this.mIsError = false;
    }

    private void clear(boolean scroll) {
        this.mHistory.enter("");
        this.mDisplay.setText("", scroll ? CalculatorDisplay.Scroll.UP : CalculatorDisplay.Scroll.NONE);
        cleared();
    }

    /* access modifiers changed from: package-private */
    public void cleared() {
        this.mResult = "";
        this.mIsError = false;
        updateHistory();
        setDeleteMode(0);
    }

    /* access modifiers changed from: package-private */
    public boolean acceptInsert(String delta) {
        String text = getText();
        return !this.mIsError && (!this.mResult.equals(text) || isOperator(delta) || this.mDisplay.getSelectionStart() != text.length());
    }

    /* access modifiers changed from: package-private */
    public void onDelete() {
        if (getText().equals(this.mResult) || this.mIsError) {
            clear(false);
            return;
        }
        // this.mDisplay.dispatchKeyEvent(new KeyEvent(0, KeyEvent.KEYCODE_DEL));

        String text = getText();
        String newText = text.substring(0, text.length() - 1);
        this.mDisplay.setText(newText, CalculatorDisplay.Scroll.NONE);
        this.mResult = "";
    }

    /* access modifiers changed from: package-private */
    public void onClear() {
        boolean z = true;
        if (this.mDeleteMode != 1) {
            z = false;
        }
        clear(z);
    }

    /* access modifiers changed from: package-private */
    public void onEnter() {
        if (this.mDeleteMode == 1) {
            clearWithHistory(false);
        } else {
            evaluateAndShowResult(getText(), CalculatorDisplay.Scroll.UP);
        }
    }

    public void evaluateAndShowResult(String text, CalculatorDisplay.Scroll scroll) {
        try {
            String result = evaluate(text);
            if (!text.equals(result)) {
                this.mHistory.enter(text);
                this.mResult = result;
                this.mDisplay.setText(this.mResult, scroll);
                setDeleteMode(1);
            }
        } catch (SyntaxException e) {
            this.mIsError = true;
            this.mResult = this.mErrorString;
            this.mDisplay.setText(this.mResult, scroll);
            setDeleteMode(1);
        }
    }

    /* access modifiers changed from: package-private */
    public void onUp() {
        String text = getText();
        if (!text.equals(this.mResult)) {
            this.mHistory.update(text);
        }
        if (this.mHistory.moveToPrevious()) {
            this.mDisplay.setText(this.mHistory.getText(), CalculatorDisplay.Scroll.DOWN);
        }
    }

    /* access modifiers changed from: package-private */
    public void onDown() {
        String text = getText();
        if (!text.equals(this.mResult)) {
            this.mHistory.update(text);
        }
        if (this.mHistory.moveToNext()) {
            this.mDisplay.setText(this.mHistory.getText(), CalculatorDisplay.Scroll.UP);
        }
    }

    /* access modifiers changed from: package-private */
    public void updateHistory() {
        String text = getText();
        if (TextUtils.isEmpty(text) || TextUtils.equals(text, this.mErrorString) || !text.equals(this.mResult)) {
            this.mHistory.update(getText());
        } else {
            this.mHistory.update("?");
        }
    }

    /* access modifiers changed from: package-private */
    public String evaluate(String input) throws SyntaxException {
        if (input.trim().equals("")) {
            return "";
        }
        int size = input.length();
        while (size > 0 && isOperator(input.charAt(size - 1))) {
            input = input.substring(0, size - 1);
            size--;
        }
        String replaced = replaceTranslations(input);
        double value = this.mSymbols.eval(replaced);
        String result = "";
        for (int precision = this.mLineLength; precision > 6; precision--) {
            result = tryFormattingWithPrecision(value, precision);
            if (result.length() <= this.mLineLength) {
                break;
            }
        }
        return result.replace('-', (char) 8722).replace("Infinity", mContext.getString(R.string.error)).replace("NaN", mContext.getString(R.string.error));
    }

    private void addTranslation(HashMap<String, String> map, int t, int m) {
        Resources res = this.mContext.getResources();
        String translated = res.getString(t);
        String math = res.getString(m);
        addTranslation(map, translated, math);
    }

    private void addTranslation(HashMap<String, String> map, String translated, String math) {
        if (!TextUtils.equals(translated, math)) {
            map.put(translated, math);
        }
    }

    private String replaceTranslations(String input) {
        if (this.mTranslationsSet == null) {
            HashMap<String, String> map = new HashMap<>();
            addTranslation(map, R.string.sin, R.string.sin_mathematical_value);
            addTranslation(map, R.string.cos, R.string.cos_mathematical_value);
            addTranslation(map, R.string.tan, R.string.tan_mathematical_value);
            addTranslation(map, R.string.e, R.string.e_mathematical_value);
            addTranslation(map, R.string.ln, R.string.ln_mathematical_value);
            addTranslation(map, R.string.lg, R.string.lg_mathematical_value);

            this.mTranslationsSet = map.entrySet();
        }
        String result = input;
        for (Map.Entry<String, String> entry : this.mTranslationsSet) {
            result = input.replace(entry.getKey(), entry.getValue());
        }

        if ("ar".equals(Locale.getDefault().getLanguage())) {
            result = convertArToDec(result);
        }

        return result;
    }

    private HashMap<String, String> arabicToDecimalMap;

    private HashMap<String, String> getArabicToDecimalMap() {
        if (arabicToDecimalMap == null) {
            arabicToDecimalMap = new HashMap<>();
            arabicToDecimalMap.put("٠", "0");
            arabicToDecimalMap.put("١", "1");
            arabicToDecimalMap.put("٢", "2");
            arabicToDecimalMap.put("٣", "3");
            arabicToDecimalMap.put("٤", "4");
            arabicToDecimalMap.put("٥", "5");
            arabicToDecimalMap.put("٦", "6");
            arabicToDecimalMap.put("٧", "7");
            arabicToDecimalMap.put("٨", "8");
            arabicToDecimalMap.put("٩", "9");
        }

        return arabicToDecimalMap;
    }

    private String convertArToDec(String input) {
        HashMap<String, String> map = getArabicToDecimalMap();
        String result = input;
        for (String c : map.keySet()) {
            result = result.replace(c, map.get(c));
        }
        return result;
    }

    private String convertDec2Ar(String input) {
        HashMap<String, String> map = getArabicToDecimalMap();
        String result = input;
        for (String c : map.keySet()) {
            result = result.replace(map.get(c), c);
        }
        return result;
    }

    private String tryFormattingWithPrecision(double value, int precision) {
        String mantissa;
        String result;
        String result2 = String.format(Locale.US, "%" + this.mLineLength + "." + precision + "g", Double.valueOf(value));
        if (result2.equals("NaN")) {
            this.mIsError = true;
            return this.mErrorString;
        }
        String exponent = null;
        int e = result2.indexOf(101);
        if (e != -1) {
            mantissa = result2.substring(0, e);
            String exponent2 = result2.substring(e + 1);
            if (exponent2.startsWith("+")) {
                exponent2 = exponent2.substring(1);
            }
            exponent = String.valueOf(Integer.parseInt(exponent2));
        } else {
            mantissa = result2;
        }
        int period = mantissa.indexOf(46);
        if (period == -1) {
            period = mantissa.indexOf(44);
        }
        if (period != -1) {
            while (mantissa.length() > 0 && mantissa.endsWith("0")) {
                mantissa = mantissa.substring(0, mantissa.length() - 1);
            }
            if (mantissa.length() == period + 1) {
                mantissa = mantissa.substring(0, mantissa.length() - 1);
            }
        }
        if (exponent != null) {
            result = mantissa + 'e' + exponent;
        } else {
            result = mantissa;
        }
        if ("ar".equals(Locale.getDefault().getLanguage())) {
            result = convertDec2Ar(result);
        }
        return result;
    }

    static boolean isOperator(String text) {
        return text.length() == 1 && isOperator(text.charAt(0));
    }

    static boolean isOperator(char c) {
        return "+−×÷/*".indexOf(c) != -1;
    }
}
